package com.crystal.jcms.shpz;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.crystal.constant.Constant;
import com.crystal.jcms.adapter.MyAdapter;
import com.crystal.jcms.utils.DialogUtils;
import com.crystal.jcms.utils.ShowMsgUtils;
import com.crystal.jcms.utils.SpUtils;
import com.crystal.jcms.utils.RequestUtils;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;

public class ActivityList extends Activity implements OnClickListener {
	private Context mContext;
	private ArrayList<Map<String, String>> list;
	private MyAdapter adapter;
	private ListView listview;
	private String flag = "", strNbzlh = "", strTestNo = "", strId = "", strItemName = "", dbType = "";
	boolean isSelect = true;
	public Dialog mLoading;
	private Button button_backward;

	@SuppressLint("InflateParams")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mContext = this;
		setContentView(R.layout.activity_list);
		initWidget();
		initData();

	}

	private class listItemOnClick implements OnItemClickListener {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			strTestNo = list.get(position).get("TestNo");
			strId = list.get(position).get("Id");
			Message message = new Message();
			message.what = Constant.SHOWPAGE;
			handler.sendMessage(message);
		}
	}

	private void initWidget() {
		flag = getIntent().getStringExtra("Flag");
		strNbzlh = getIntent().getStringExtra("Nbzlh");
		strItemName = getIntent().getStringExtra("ItemName");
		dbType = getIntent().getStringExtra("dbType");
		ActionBar actionBar = getActionBar();
		actionBar.setDisplayShowHomeEnabled(false);
		actionBar.setDisplayShowTitleEnabled(false);
		actionBar.setDisplayShowCustomEnabled(true);
		View customView = LayoutInflater.from(this).inflate(R.layout.custom_view, null);
		TextView mTitleTextView = (TextView) customView.findViewById(R.id.title_text);
		mTitleTextView.setText(flag);
		CheckBox cbSelectAll = (CheckBox) customView.findViewById(R.id.cb_selectAll);
		cbSelectAll.setOnClickListener(this);
		actionBar.setCustomView(customView);
		listview = (ListView) findViewById(R.id.listview_list);
		listview.setOnItemClickListener(new listItemOnClick());
		button_backward = (Button) findViewById(R.id.button_backward);
		button_backward.setOnClickListener(this);
	}

	private void initData() {
		mLoading = DialogUtils.createLoadingDialog(mContext, "加载中...");
		mLoading.show();
		new Thread(new Runnable() {
			public void run() {
				loadData();
			}
		}).start();
	}

	public void loadData() {
		list = new ArrayList<Map<String, String>>();
		Map<String, String> param = new HashMap<String, String>();
		param.put("type", flag);
		param.put("nbzlh", strNbzlh);
		param.put("dbType", dbType);
		String result = RequestUtils.doPost(mContext, "list.xml", "GetItemList", param);
		Message message = new Message();
		message.what = Constant.SHOWTOAST;
		if (result.contains("500_")) {
			message.obj = result.substring(4);
			handler.sendMessage(message);
			return;
		}
		try {
			JSONObject jsonResult = new JSONObject(result);
			if (!jsonResult.get("Result").equals("")) {
				JSONArray jsonArray = jsonResult.getJSONArray("Result");
				for (int i = 0; i < jsonArray.length(); i++) {
					JSONObject object = jsonArray.getJSONObject(i);
					Map<String, String> map = new HashMap<String, String>();
					map.put("Id", object.getString("Id"));
					map.put("TestNo", object.getString("TestNo"));
					map.put("ReportNo", object.getString("ReportNo"));
					map.put("ProName", object.getString("ProName"));
					map.put("TestRen", object.getString("TestRen"));
					map.put("TestDate", object.getString("TestDate"));
					map.put("QiLing", object.getString("QiLing"));
					list.add(map);
				}
				message.what = Constant.BINDLISTVIEW;
			} else {
				message.obj = "无数据！";
			}
		} catch (JSONException e) {
			e.printStackTrace();
			message.obj = e.getMessage();
		}
		handler.sendMessage(message);
	}

	// 报告审核批准
	public void ReportCheck() {
		mLoading = DialogUtils.createLoadingDialog(mContext, "审批中...");
		mLoading.show();
		List<String> testNos = new ArrayList<String>();
		for (int i = 0; i < list.size(); i++) {
			boolean isSelected = MyAdapter.getIsSelected().get(i);
			if (isSelected) {
				testNos.add(list.get(i).get("TestNo"));
			}
		}
		String strTestNos = "";
		if (testNos.size() > 0) {
			for (int i = 0; i < testNos.size(); i++) {
				strTestNos += ",'" + testNos.get(i) + "'";
			}
		}
		if (strTestNos.length() == 0) {
			Message message = new Message();
			message.what = Constant.SHOWTOAST;
			message.obj = "请选择要审批的数据！";
			handler.sendMessage(message);
			return;
		}
		strTestNos = strTestNos.substring(1);
		Map<String, String> params = new HashMap<String, String>();
		params.put("type", flag);
		params.put("nbzlh", strNbzlh);
		params.put("username", (String) SpUtils.get(mContext, "UserName", ""));
		params.put("testnos", "(" + strTestNos + ")");
		params.put("dbType", dbType);
		RequestUtils.doPostAsyn(mContext, "shenpi.xml", "ExecuteCheck", params, new RequestUtils.CallBack() {

			@Override
			public void onRequestComplete(String result) {
				Message message = new Message();
				message.what = Constant.SHOWTOAST;
				try {
					if (result.contains("500_")) {
						message.obj = result.substring(4);
						handler.sendMessage(message);
						return;
					}
					JSONObject jsonResult = new JSONObject(result);
					if (jsonResult.getBoolean("ReturnData")) {
						// 审核通过，重新加载数据
						loadData();
					}
				} catch (JSONException e) {
					e.printStackTrace();
					message.obj = e.getMessage();
					handler.sendMessage(message);
				}
			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case Constant.CALLBACKCODE:
			initData();
			break;
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.cb_selectAll:
			selectAll();
			break;
		case R.id.button_backward:
			finish();
			break;
		}
	}

	private void selectAll() {
		if (isSelect) {
			isSelect = false;
			for (int i = 0; i < list.size(); i++) {
				MyAdapter.getIsSelected().put(i, true);
			}
		} else {
			isSelect = true;
			for (int i = 0; i < list.size(); i++) {
				MyAdapter.getIsSelected().put(i, false);
			}
		}
		adapter.notifyDataSetChanged();
	}

	@SuppressLint("HandlerLeak")
	public Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (mLoading != null) {
				if (mLoading.isShowing()) {
					mLoading.dismiss();
				}
			}
			switch (msg.what) {
			case Constant.SHOWPAGE:
				Intent intent = new Intent(ActivityList.this, ActivityCard.class);
				intent.putExtra("Flag", flag);
				intent.putExtra("Nbzlh", strNbzlh);
				intent.putExtra("TestNo", strTestNo);
				intent.putExtra("ItemName", strItemName);
				intent.putExtra("Id", strId);
				intent.putExtra("dbType", dbType);
				startActivityForResult(intent, Constant.CALLBACKCODE);
				break;
			case Constant.BINDLISTVIEW:
				adapter = new MyAdapter(list, ActivityList.this);
				listview.setAdapter(adapter);
				break;
			case Constant.SHOWTOAST:
				ShowMsgUtils.ShowToast(mContext, (String) msg.obj);
				break;
			case Constant.SHOWMESSAGE:
				ShowMsgUtils.ShowMessage(mContext, (String) msg.obj);
				break;
			}
		}
	};

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		if (flag.equals("报告批准")) {
			MenuItem item = menu.findItem(R.id.action_operate);
			item.setTitle("批准");
		}
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			return true;
		case R.id.action_operate:
			ReportCheck();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

}
